#include "GLSLShader.h"

namespace lib3dw
{
	GLSLShader::GLSLShader(const char* filename, GLenum shaderType)
	{
		file = filename;
		const char *shader = NULL;
		id = glCreateShader(shaderType);
		shader = ReadShaderFile(filename);
		const char* shaderRef = shader;
		glShaderSource(id, 1, &shaderRef, NULL);
		glCompileShader(id);
		CheckCompilerLog();
	}

	GLSLShader::~GLSLShader()
	{
		
	}

	GLuint GLSLShader::GetShaderID() const
	{
		return id;
	}

	const char* GLSLShader::ReadShaderFile(const char* shaderFile)
	{
		FILE* fp;
		char* content = NULL;
		const char* fn = shaderFile;
		int	count=0;

		if (fn != NULL)
		{
			fp = fopen(fn,"rt");
			if (fp != NULL)
			{
				fseek(fp, 0, SEEK_END);
				count = ftell(fp);
				rewind(fp);

				if (count > 0) 
				{
					content = (char *)malloc(sizeof(char) * (count+1));
					count = fread(content,sizeof(char),count,fp);
					content[count] = '\0';
				}
				fclose(fp);
			}
		}
		return content;
	}
	
	void GLSLShader::CheckCompilerLog()
	{
		GLint blen = 0;	
		GLsizei slen = 0;

		glGetShaderiv(id, GL_INFO_LOG_LENGTH , &blen);       
		if (blen > 1)
		{
			GLchar* compiler_log = (GLchar*)malloc(blen);
			glGetInfoLogARB((GLhandleARB)id, blen, &slen, compiler_log);
			std::cout << "compiler_log for: " << file << "\n" << compiler_log;
			free (compiler_log);
		}
	}
}